﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;

namespace SplitCode
{
    public class PDFCoder : ICoder, IDisposable
    {
        private PdfReader _reader;
        private string _inputImageName;
        private ConfObj _config;

        public void Prepare(ConfObj config)
        {
            _config = config;
        }

        public int LoadImage(string fileName)
        {
            _inputImageName = fileName;
            _reader = new PdfReader(fileName);
            return _reader.NumberOfPages;
        }

        public void Save(int pageNum)
        {
            pageNum += 1;   // 1-based
            string outputFileName = null;

            if (String.IsNullOrEmpty(_config.outDir))
            {
                outputFileName = Path.Combine(Path.GetDirectoryName(_inputImageName), String.Format("{0}_{1}.pdf",
                    Path.GetFileNameWithoutExtension(_inputImageName), pageNum));
            }
            else
            {
                outputFileName = Path.Combine(_config.outDir, String.Format("{0}_{1}.pdf",
                    Path.GetFileNameWithoutExtension(_inputImageName), pageNum));
            }

            if (!_config.doOverwrite)
            {
                outputFileName = HelperMethods.ModifyFileName(outputFileName);
            }

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, new FileStream(outputFileName, FileMode.Create));
            doc.Open();
            copy.AddPage(copy.GetImportedPage(_reader, pageNum));

            doc.Close();
        }

        public void Close()
        {
            _reader.Close();
        }

        public void Dispose()
        {
            _reader.Close();
        }
    }
}
